<script setup>
import FormItemSearch from '@/components/form/FormItemSearch.vue'
import TableColumnIndex from '@/components/table/TableColumnIndex.vue'
import { usePagination, useRequest, useDialog } from '@/hooks'
import { deviceApi, versionApi } from '@/api'
import DeviceFormDialog from './DeviceFormDialog.vue'
import SendCommandDialog from './SendCommandDialog.vue'
import SteeringEngineDialog from './SteeringEngineDialog.vue'
import VersionManager from './VersionManager.vue'
import Viewer from './Viewer.vue'

const STATUS = ['离线', '在线']
const STATUS_COLORS = ['text-danger', 'text-success']

const title = computed(() => useRoute().meta.title ?? '设备列表')

const form = ref({
  deviceCode: '',
  deviceName: '',
  deviceStatus: '',
  groupId: ''
})
const formRef = ref()
function reset() {
  formRef.value.resetFields()
  search()
}

const { pageSize, currentPage, pageSizes } = usePagination({
  onChange: () => refresh()
})

const { refresh, data, count } = useRequest(deviceApi.getDeviceList, {
  initialData: [],
  immediate: true,
  onSuccess: result => {
    data.value = result.list
  },
  params: () => ({
    ...form.value,
    pageNum: currentPage.value,
    pageSize: pageSize.value
  })
})

const { data: deviceGroups } = useRequest(deviceApi.getDeviceGroupList, {
  initialData: [],
  immediate: true,
  onSuccess: result => {
    deviceGroups.value = result.list
  },
  params: () => ({
    pageNum: 1,
    pageSize: 99999
  })
})

const { data: aiVersions } = useRequest(versionApi.getDeviceAIList, {
  initialData: [],
  immediate: true,
  onSuccess: result => {
    aiVersions.value = result.list
  },
  params: () => ({
    pageNum: 1,
    pageSize: 99999
  })
})

const { data: appVersions } = useRequest(versionApi.getDeviceAppList, {
  initialData: [],
  immediate: true,
  onSuccess: result => {
    appVersions.value = result.list
  },
  params: () => ({
    pageNum: 1,
    pageSize: 99999
  })
})

// versionApi.getDeviceDetailsById

function search() {
  currentPage.value = 1
  refresh()
}

const active = ref(null)
const { visible, open } = useDialog(active)
const { visible: deviceDetailVisible, open: openDeviceDetailViewer } =
  useDialog(active)

const commands = ref([])
const deviceDetail = ref()
async function getDeviceDetail(row) {
  const detailPromise = deviceApi.getDeviceDetailsById({ id: row.id })
  const commandsPromise = deviceApi.getDeviceCommandById({
    id: row.id,
    pageNum: 1,
    pageSize: 99999
  })

  const [detail, _commands] = await Promise.all([
    detailPromise,
    commandsPromise
  ])
  deviceDetail.value = detail.data
  commands.value = _commands.data.list
  openDeviceDetailViewer(row)
}

async function handleSubmit(formValue) {
  if (active.value) {
    await deviceApi.editDeviceById({ ...formValue, id: active.value.id })
  } else {
    await deviceApi.addDevice(formValue)
  }
  ElMessage.success('操作成功')
  visible.value = false
  refresh()
}

const { visible: cmdSenderVisible, open: openCommandSender } = useDialog(active)
const { visible: steeringEngineVisible, open: openSteeringEngineVisible } =
  useDialog(active)
const { visible: versionManagerVisible, open: openVersionManager } =
  useDialog(active)

async function sendCommand(params) {
  await deviceApi.addSendCommand({
    id: active.value.id,
    deviceCommand: params.deviceCommand
  })
  ElMessage.success('操作成功')
  cmdSenderVisible.value = false
}

async function submitVersion(params) {
  await deviceApi.editDeviceCommandById({
    ...params,
    deviceId: active.value.id
  })
  ElMessage.success('操作成功')
  cmdSenderVisible.value = false
  refresh()
}

async function handleRemove(ids) {
  if (!ids?.length) return ElMessage.warning('请选择要删除的设备')

  await ElMessageBox.confirm('此操作将删除选中的设备, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
  await deviceApi.delDeviceById({ ids })
  ElMessage.success('删除成功')
  refresh()
}
</script>

<template>
  <div>
    <el-card shadow="never">
      <template #header> {{ title }} </template>
      <el-form
        ref="formRef"
        :model="form"
        label-width="90px"
        label-suffix="："
        label-position="left"
        @submit.prevent="search"
      >
        <el-row :gutter="20">
          <FormItemSearch label="设备名称" prop="deviceId">
            <el-input v-model.trim="form.deviceId" clearable />
          </FormItemSearch>
          <FormItemSearch label="设备编码" prop="deviceCode">
            <el-input v-model.trim="form.deviceCode" clearable />
          </FormItemSearch>
          <FormItemSearch label="设备分组" prop="groupId">
            <el-select v-model="form.groupId" filterable clearable>
              <el-option
                v-for="item in deviceGroups"
                :key="item.id"
                :label="item.groupName"
                :value="item.id"
              />
            </el-select>
          </FormItemSearch>
          <FormItemSearch label="设备状态" prop="deviceStatus">
            <el-select v-model="form.deviceStatus" filterable clearable>
              <el-option
                v-for="(item, index) in STATUS"
                :key="index"
                :label="item"
                :value="index"
              />
            </el-select>
          </FormItemSearch>
        </el-row>

        <el-button type="primary" native-type="submit" @submit="search">
          搜索
        </el-button>
        <el-button @click="reset">重置</el-button>
        <el-button type="primary" @click="open()"> 新增 </el-button>
        <el-button type="danger" @click="open()"> 删除 </el-button>
      </el-form>
    </el-card>

    <el-card shadow="never">
      <el-table :data="data" style="width: 100%">
        <TableColumnIndex :page="currentPage" :page-size="pageSize" />
        <el-table-column prop="deviceCode" label="设备编码" />
        <el-table-column prop="deviceName" label="设备名称" />
        <el-table-column prop="groupName" label="设备分组" />
        <el-table-column prop="deviceStatus" label="设备状态">
          <template #default="{ row }">
            <span
              v-if="STATUS[row.deviceStatus]"
              :class="STATUS_COLORS[row.deviceStatus]"
            >
              {{ STATUS[row.deviceStatus] }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="deviceDescribe" label="设备描述" />
        <TableColumnTime prop="createTime" label="创建时间" />
        <el-table-column prop="createUser" label="创建者" />
        <el-table-column label="操作" align="center" width="320" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="getDeviceDetail(row)">
              查看
            </el-button>
            <el-button link type="primary" @click="open(row)"> 编辑 </el-button>
            <el-button
              link
              type="primary"
              @click="openSteeringEngineVisible(row)"
            >
              舵机
            </el-button>
            <el-button link type="primary" @click="openCommandSender(row)">
              下发
            </el-button>
            <el-button link type="primary" @click="openVersionManager(row)">
              版本设置
            </el-button>
            <el-button link type="danger" @click="handleRemove([row.id])">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="pageSizes"
        hide-on-single-page
        layout="total, sizes, prev, pager, next, jumper"
        :total="count"
        class="mt-4 justify-end"
        small
      />
    </el-card>

    <DeviceFormDialog
      v-model="visible"
      :title="active ? '编辑设备' : '新增设备'"
      :detail="active"
      :deviceGroups="deviceGroups"
      :aiVersions="aiVersions"
      :appVersions="appVersions"
      @submit="handleSubmit"
    />

    <VersionManager
      v-model="versionManagerVisible"
      title="版本管理"
      :detail="active"
      :aiVersions="aiVersions"
      :appVersions="appVersions"
      @submit="submitVersion"
    />

    <SendCommandDialog
      v-model="cmdSenderVisible"
      :title="active?.deviceCommand ? '编辑发送指令' : '新增发送指令'"
      :detail="active"
      @submit="sendCommand"
    />

    <SteeringEngineDialog
      v-model="steeringEngineVisible"
      :detail="active"
      @close="refresh()"
    />

    <Viewer
      v-model="deviceDetailVisible"
      title="设备详情"
      :detail="deviceDetail"
      :commands="commands"
      :status="STATUS"
      :statusColors="STATUS_COLORS"
    />
  </div>
</template>
